import storage from 'store'
import api from '@/api'
import { ACCESS_TOKEN } from '@/store/mutation-types'

const auth = {
  state: {
    data: {},
    access_token: ''
  },

  mutations: {
    SET_AUTH_DATA: (state, data) => {
      state.data = data
    },
    SET_ACCESS_TOKEN: (state, accessToken) => {
      state.access_token = accessToken
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        api.auth.login(userInfo).then(response => {
          const auth = response.data.data.admin
          commit('SET_ACCESS_TOKEN', auth.token)
          storage.set(ACCESS_TOKEN, auth.token, 7 * 24 * 60 * 60 * 1000)
          resolve()
        }).catch(error => {
          console.log(error)
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        api.auth.getInfo().then(response => {
          commit('SET_AUTH_DATA', response.data.data)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        api.auth.logout(state.access_token).then(() => {
          commit('SET_AUTH_DATA', {})
          commit('SET_ACCESS_TOKEN', '')
          storage.remove(ACCESS_TOKEN)
          resolve()
        }).catch(() => {
          resolve()
        }).finally(() => {
        })
      })
    }

  }
}

export default auth
